package com.crm.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.crm.entity.User;
import com.crm.repository.DepartmentRepository;
import com.crm.repository.UserRepository;
import com.crm.service.UserService;
import com.crm.service.impl.RoleServiceImpl;
import com.crm.service.impl.UserServiceImpl;
import com.crm.util.FenyeUtil;
import com.crm.util.MD5;
import com.crm.entity.Department;
import com.crm.entity.Module;

@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserServiceImpl userService;
@Autowired
private UserRepository userRepository;
@Autowired
private RoleServiceImpl roleService;

@Autowired
private DepartmentRepository depff;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@GetMapping
public FenyeUtil<User> findAll(User u,Integer page,String bmName){
	FenyeUtil<User> f = new FenyeUtil<User>();
	Pageable pageable = PageRequest.of(page-1, 10);
	Page<User> use = userService.findByUser(u, pageable,bmName);
	List<User> ulist =  use.getContent();
	System.out.println(ulist);
	int count=(int) use.getTotalElements();
		  
	f.setCount(count);
	f.setData(ulist);
       return f;	
}




/**
 * 获取全部部门
 * 
 */
@RequestMapping("/getdep")
@GetMapping
public List<Department> dep(){
	return depff.findAll();
}

@PostMapping
public Object AddUser(User u,Integer bmId) {
	try {
		u.setUserId(UUID.randomUUID().toString());
		u.setUserPassWord(MD5.JiaM("ysd123"));
		u.setUserCreateTime(sdf.format(new Date()));
		u.setBm(depff.findBybmId(bmId));
		u.setUserIsLockout(0);
		u.setUserPassWrongCout(0);
		u.setCheckState("未签到");
		if(u.getBm()!=null) {
			userService.AddAndUpdate(u);
			 return "添加成功";
		}else {
			return "输入的部门不存在";
		}
	} catch (Exception e) {
		// TODO: handle exception
		return "添加失败";
	}
	
}
@PutMapping
public Object UpUser(User u,Integer bmId) {
	try {
		Optional<User> user=userRepository.findById(u.getUserId());//获取原先user的数据
		User u1=user.get();
		//存值
		u1.setUserEmail(u.getUserEmail());
		u1.setUserPassWord(u.getUserPassWord());
		u1.setUserName(u.getUserName());
		u1.setUserTelephone(u.getUserTelephone());
		u1.setUserUpdateTime(sdf.format(new Date()));
		 userService.AddAndUpdate(u1);
		 
		 
		 u1.setBm(depff.findBybmId(bmId));
			if(u1.getBm()!=null) {
				userService.AddAndUpdate(u1);
				 return "修改成功";
			}else {
				return "输入的部门不存在";
			}
	} catch (Exception e) {
		// TODO: handle exception
		return "修改失败";
	}
	
} 
@DeleteMapping
public Object Delete(String id) {
	try {
		userService.DelUser(id);
		return "删除成功";
	} catch (Exception e) {
		
		return "删除失败";
	}
}

/**
 * 忘记密码更换新密码
 * @param uname
 * @param phone
 * @param password
 * @return
 */
@PutMapping
@RequestMapping("/forgetPwd")
public String forgetPwd(String uname,String phone,String password) {
	return userService.FinPwdAndNewPwd(uname, phone, password);
}
/**
 * 检查是否存在账号
 * @param loginName
 * @return
 */
@GetMapping("findId/jiancha")
public Integer findId(String userName){
    String id = userRepository.findId(userName);
    if(id!=null){
        return  1;
    }else {
        return 0;
    }
}
/**
 * 不同用户显示不同权限
 * @param id
 * @return
 */
@GetMapping("/getUserModule")
public Object ModuleTree(String id) {
	  
	//封装成Tree要的数据
	List<Map<String,Object>> list = new ArrayList<>();
	//模块全部数据
    List<Module> All=userService.getUser_Role_ModuleByUserId(id);
    System.out.println(id);
	for (Module p : All) {
	
	if(p.getParentId()==null) {//判断是否是父节点
		Map<String,Object> map =new HashMap<>();
		map.put("title", p.getModuleName());
		map.put("id", p.getModuleId());
		//节点路径
		map.put("path", p.getModuleUrl());
		//节点权重
		//map.put("weight", p.getWeight());
		//传一个父节点的id, 方便js判断
	//	map.put("parentid", 1);
		//map.put("spread", true);//是否直接展开
		//子节点,遍历循环 递归
		map.put("children", getChildren(p,All));
		list.add(map);
	}
   
	}
	return list;
}
public List<Object> getChildren(Module p,List<Module> module){
	//用list集合封装children的对象数组
    List<Object> list = new ArrayList<>();
   
        for (Module d : module) {
        	//判断子节点是否属于相应的父节点
        if(p.getModuleId().equals(d.getParentId())) {
        	
        	//判断有没有子节点,没有子节点的话就是父节点
        	if(p.getChildren()==null) {
         	   p.setChildren(new ArrayList<Module>());
         	}
        	//创建Map集合 必须放这个位置,每次符合条件都要创建,不然的话加载的数据只有最后一个
        	 Map<String,Object> map =new HashMap<>();
        	//子节点的title数据
        	map.put("title", d.getModuleName());
        	//把子节点的id传到树里面
        	map.put("id", d.getModuleId());
        	//方便在添加的时候判断是不是在子节点下添加
        //	map.put("pan", 2);
        	//节点路径
			map.put("c", d.getModuleUrl());
			//节点权重
		//	map.put("weight", d.getModuleWeight());
        	//子节点children的对象数组
        	map.put("children", getChildren(d, module));
        	list.add(map);
        }
    
    }
    return list;
}
/**
 * 锁定
 * @param id
 * @param islock
 * @return
 */
@PutMapping("/lock")
public Object jieFeng(String id,Integer islock) {
	System.out.println(id);
	if(islock==1) {//等于1则为解封
		return userService.jieFeng(id);
	}else {
		return userService.suoDing(id);
	}
	
} 
/**
 * 重置密码
 * @param uname
 * @return
 */
@PutMapping("/chongzhi")
public Object  reSetPassWord (String uname) {
	return userRepository.updPwdByNewPwd(uname, MD5.JiaM("ysd123"));
}
/**
 * 获取角色列表
 * @return
 */
@GetMapping("/role")
public Object getRlist(String id) {
	System.out.println(roleService.getRoleByUserId(id));
	return roleService.getRoleByUserId(id);
}
/**
 * 修改角色用户的关系
 * @param id
 * @param roleId
 * @return
 */
@PutMapping("/commit")
public Object User_RoleManage(String id,String roleId) {
	return userService.user_roleManage(id, roleId);
}


/**
 * 修改签到状态
 * @param id
 * @param checkState
 * @return
 */
@PutMapping("/updateCheckState")
public Object updateCheckState(String id,String checkState,String userName,Integer type) {
	return userService.updateCheckState(id, checkState,userName,type);
}


@GetMapping("/allUserName")
public Object getAllUserName() {
	
	return userRepository.findAll();
}

/**
 * 修改密码
 * @param id
 * @param password
 * @return
 */
@PutMapping("/xiuPass")
public Object updatePassWord(String id,String password){
	if(password!=null&&id!=null&&id!=""&&password!="") {
		Integer integer = userRepository.xiugaiPassWord(id, MD5.JiaM(password));
		if(integer>0){
			return 1;
		}else{
			return 0;
		}
	}else {
		return 0;
	}
	
	
}
@GetMapping("/cha")
public Object cha(String id,String phone){
	System.out.println(id+"------------------"+phone);
	User cha = userRepository.cha(id, phone); 
	if(cha!=null) {
		return 0;
	}else {
		return 1;
	}
}




}
